package com.example.demo.baidu;

import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.util.Base64Util;
import com.example.demo.baidu.utils.FileUtil;
import com.example.demo.baidu.utils.HttpUtil;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author void
 * @date 2021/6/3 15:44
 * @desc
 */
public class IdCard {
    public static String httpAPI() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            // 本地文件路径
            String filePath = "D://3496e65d9806b7167faa71d1a7a024c.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = BaiduConstant.ACCESS_TOKEN;

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void SDK(){
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(BaiduConstant.APP_ID, BaiduConstant.API_KEY, BaiduConstant.SECRET_KEY);

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(20000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        String path = "D://3496e65d9806b7167faa71d1a7a024c.jpg";

        String idCardSide = "front";

        JSONObject res = client.idcard(path, idCardSide, options);
        System.out.println(res.toString());
        System.out.println(res.toString(2));
    }

    public static void main(String[] args) {
//        httpAPI();
        SDK();
    }
}
